#!/bin/bash

LOGFILE=/var/log/script-ssl.log
VERBOSE=0

#
# function to output help
#
function usage
{
        echo Usage $0
        echo "  -h, --help: display this page"
        echo "  -k, --key <filename>: name of the keyfile (default ist client.key)"
	echo "	-d, --debug"
	echo "	-v, --verbose"
}

function error
{
	echo $(date "+%Y-%m-%d %H:%M") [$0] ERROR $1 >> $LOGFILE
	echo [$0]: ERROR $1 1>&2
}

function debug
{
	if [ $VERBOSE -gt 1 ]
	then
		echo $(date "+%Y-%m-%d %H:%M") [$0] DEBUG $1 >> $LOGFILE
	fi
}

function log
{
	if [ $VERBOSE -gt 0 ]
	then
		echo $(date "+%Y-%m-%d %H:%M") [$0] LOG   $1 >> $LOGFILE
	fi
}


#
# function to check a simple yes/no question
# returns 0 if answer is yes (or no question was asked)
# parameter $1: 0 if ask no question
# paraneter $2: question text
#
function checkyN
{
	log "CheckyN start"
        if [ $1 -eq 0 ]
        then
		log "P1 == 0"
                return 0
        fi
        echo $2 "(y/N)"
        read answer
        if [ "$answer" = "" ]
        then
		log "default answer"
                answer=n
        fi
        case $answer in
                Y | y | Y* | y*)
			log "answer = $answer (Y)"
                        return 0
                        ;;
                n | N | n* | N*)
			log "answer = $answer (N)"
                        return 2
                        ;;
        esac
}

log "start script"

keyfilename=client.key

# check the input parameters
while [ "$1" != "" ]
do
        case $1 in
                -k | --key )    shift
                                keyfilename=$1
                                ;;
                -h | --help )   usage
                                exit
                                ;;
		-v | --verbose) VERBOSE=1
				;;
		-d | --debug)	VERBOSE=2
				;;
                *)              error "Unknown Parameter $1"
                                usage
                                exit 1
        esac
        shift
done
log "parameter done"

if [ -f $keyfilename ]
then
	ok=0
else
	error "$keyfilename nicht gefunden."
	exit 3
fi

filename=${keyfilename%.*}
csrfilename=$filename.csr

if [ -f $csrfilename ]
then
	checkyN 1 "$csrfilename existiert bereits. Überschreiben?"
	if [ $? -ne 0 ]
	then
		log "User abbruch - Datei überschreiben"
		exit 5
	fi
fi

checkyN $ok "Wollen Sie wirklich fortfahren?"
if [ $? -ne 0 ]
then
	exit 4
fi

log "call: openssl req -new -key $keyfilename -out $csrfilename"
openssl req -new -key $keyfilename -out $csrfilename

